//
//  SelectCityViewController.m
//  WWTQ
//
//  Created by JP on 2018/10/29.
//  Copyright © 2018年 Jqert. All rights reserved.
//

#import "SelectCityViewController.h"
#import "SelectcityModel.h"
#import "SelectCityDetailModel.h"

#import <MJExtension.h>

@interface SelectCityViewController () <UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating>

@property (nonatomic, copy) NSArray *selectCityArr;
@property (nonatomic, strong) NSMutableArray *results;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UISearchController *searchController;

@end

@implementation SelectCityViewController

- (NSArray *)selectCityArr {
    if (!_selectCityArr) {
        _selectCityArr = [SelectCityModel mj_objectArrayWithFilename:@"CityName.plist"];
    }
    return _selectCityArr;
}

- (NSMutableArray *)results {
    if (!_results) {
        _results = [[NSMutableArray alloc] init];
    }
    return _results;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight, ScreenW, ScreenH) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.sectionIndexColor = [[UIColor blueColor] colorWithAlphaComponent:0.7];
        _tableView.sectionIndexBackgroundColor = [UIColor clearColor];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initBase];
    
    [self setUpTabelView];
}

- (void)initBase {
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"添加城市";
}

- (void)setUpTabelView {
    [self.view addSubview:self.tableView];
    
    UIImageView *backImageV = [[UIImageView alloc] initWithImage:self.image];
    self.tableView.backgroundView = backImageV;
    
    UIToolbar *bar = [[UIToolbar alloc] init];
    bar.barStyle = UIBarStyleDefault;
    bar.alpha = 0.8;
    bar.frame = [UIScreen mainScreen].bounds;
    [backImageV addSubview:bar];
    
    // 创建UISearchController, 这里使用当前控制器来展示结果
    UISearchController *search = [[UISearchController alloc]initWithSearchResultsController:nil];
    // 设置结果更新代理
    search.searchResultsUpdater = self;
    // 因为在当前控制器展示结果, 所以不需要这个透明视图
    search.dimsBackgroundDuringPresentation = NO;
    self.searchController = search;
    // 将searchBar赋值给tableView的tableHeaderView
    self.tableView.tableHeaderView = search.searchBar;
    self.tableView.tableHeaderView.backgroundColor = RGB(103,155,205);
    
    search.searchBar.placeholder = @"添加城市/地区";
    search.searchBar.backgroundColor = [UIColor clearColor];
    for (UIView *sview in search.searchBar.subviews.firstObject.subviews) {
        if ([sview isKindOfClass:[UIImageView class]]) {
            [sview removeFromSuperview];
        }
    }
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.searchController.active) {
        return 1;
    }
    return self.selectCityArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.searchController.active) {
        return self.results.count;
    }
    SelectCityModel *model = self.selectCityArr[section];
    NSArray *arr = model.citys;
    return arr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (self.searchController.active) {
        return 0;
    }
    return 20;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectZero];
//    headerView.backgroundColor = RGB(103,155,205);
    headerView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.3];
    
    UILabel *sectionTitle = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 40, 20)];
    sectionTitle.textAlignment = 1;
    sectionTitle.textColor = [UIColor blackColor];
    sectionTitle.font = [UIFont fontWithName:@"Verdana" size:15];
    SelectCityModel *model = [self.selectCityArr objectAtIndex:section];
    sectionTitle.text = [model.solr uppercaseString];
    [headerView addSubview:sectionTitle];

    return headerView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *celliD = @"cell1";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:celliD];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:celliD];
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.textColor = ZYTBlack1Color;
    }
    SelectCityDetailModel *detailModel;
    if (self.searchController.active) {
        detailModel = self.results[indexPath.row];
    } else {
        SelectCityModel *model = self.selectCityArr[indexPath.section];
        detailModel = model.citys[indexPath.row];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"%@ - %@", detailModel.name, detailModel.province];
    return cell;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    NSMutableArray *mutArr = [[NSMutableArray alloc] init];
    for (SelectCityModel *model in self.selectCityArr) {
        NSString *solr = model.solr;
        [mutArr addObject:solr];
    }
    return mutArr;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SelectCityDetailModel *detailModel;
    if (self.searchController.active) {
        detailModel = self.results[indexPath.row];
    } else {
        SelectCityModel *model = self.selectCityArr[indexPath.section];
        detailModel = model.citys[indexPath.row];
    }
    for (NSDictionary *dict in self.allCityArr) {
        if ([dict[@"name"] isEqualToString:detailModel.name]) {
            buildErrorSVP(@"请勿重复添加");
            return ;
        }
    }
    NSDictionary *cityDic = [NSDictionary dictionaryWithObjectsAndKeys:detailModel.code, @"code", detailModel.name, @"name", nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:SELECTCITY object:nil userInfo:cityDic];
    
    self.searchController.active = NO;
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark - UISearchResultsUpdating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    NSString *inputStr = searchController.searchBar.text;
    if (self.results.count > 0) {
        [self.results removeAllObjects];
    }
    for (SelectCityModel *model in self.selectCityArr) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains %@ or shortpinyin contains %@ or fullpinyin contains %@", inputStr, inputStr, inputStr]; // name\pinYin\pinYinHead不是随便写的, 是模型中的属性; contains是包含后面%@这个字符串
//        self.results = [NSMutableArray arrayWithArray:[model.citys filteredArrayUsingPredicate:predicate]]; // 这个self.resultCities可以是一个不可变数组
        NSArray *arr = [model.citys filteredArrayUsingPredicate:predicate];
        [self.results addObjectsFromArray:arr];
    }

    [self.tableView reloadData];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.tableView resignFirstResponder];
}

-(void)viewDidLayoutSubviews {
    if(self.searchController.active) {
        [self.tableView setFrame:CGRectMake(0,20,ScreenW,ScreenH -20)];
    } else {
        self.tableView.frame =self.view.bounds;
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}



@end
